import { defineStore } from 'pinia'
import api from '@/api'
import { getUserProfile, updateUserProfile } from '@/api/user'
import { ElMessage } from 'element-plus'
import { formatAvatarUrl } from '@/utils/format'
import { useTabsStore } from './tabs'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    username: localStorage.getItem('username') || '',
    isLoggedIn: !!localStorage.getItem('token'),
    userInfo: JSON.parse(localStorage.getItem('user_info') || '{}'),
    permissions: JSON.parse(localStorage.getItem('permissions') || '[]')
  }),
  
  getters: {
    getToken: (state) => state.token,
    getUsername: (state) => state.username,
    getUserInfo: (state) => state.userInfo,
    getAvatar: (state) => {
      // 返回用户头像，可能是base64编码的图片数据或路径
      return state.userInfo.avatar || ''
    },
    getUserRoles: (state) => state.userInfo.roles || []
  },
  
  actions: {
    async login(username, password) {
      try {
        const response = await api.login(username, password)
        
        if (response && response.data && response.data.access_token) {
          this.token = response.data.access_token
          this.username = username
          this.isLoggedIn = true
          
          // 保存到本地存储
          localStorage.setItem('token', response.data.access_token)
          localStorage.setItem('username', username)
          
          // 登录成功后获取用户信息
          await this.fetchUserInfo()
          
          return true
        }
        
        return false
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('用户名或密码错误')
        return false
      }
    },
    
    logout() {
      this.token = ''
      this.username = ''
      this.isLoggedIn = false
      this.userInfo = {}
      this.permissions = []
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('user_info')
      localStorage.removeItem('permissions')
      
      // 清除所有标签页，只保留首页
      const tabsStore = useTabsStore()
      tabsStore.closeAllTabs()
    },
    
    // 获取用户信息
    async fetchUserInfo() {
      if (!this.isLoggedIn) return
      
      try {
        const response = await getUserProfile()
        if (response && response.data) {
          this.userInfo = response.data
          localStorage.setItem('user_info', JSON.stringify(response.data))
          
          // 提取权限
          const permissions = []
          if (response.data.roles) {
            response.data.roles.forEach(role => {
              if (role.permissions) {
                role.permissions.forEach(permission => {
                  if (!permissions.includes(permission.code)) {
                    permissions.push(permission.code)
                  }
                })
              }
            })
          }
          
          if (permissions.length === 0) {
            console.warn('未找到用户权限，尝试从专门的API获取')
            try {
              const permResponse = await api.getUserPermissions()
              if (permResponse && permResponse.data && Array.isArray(permResponse.data)) {
                this.permissions = permResponse.data
                localStorage.setItem('permissions', JSON.stringify(permResponse.data))
                return
              }
            } catch (permError) {
              console.error('获取权限失败:', permError)
            }
          }
          
          this.permissions = permissions
          localStorage.setItem('permissions', JSON.stringify(permissions))
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },
    
    // 更新用户信息
    async updateUserInfo(userData) {
      try {
        const response = await updateUserProfile(userData)
        if (response && response.data) {
          this.userInfo = { ...this.userInfo, ...userData }
          localStorage.setItem('user_info', JSON.stringify(this.userInfo))
          return true
        }
        return false
      } catch (error) {
        console.error('更新用户信息失败:', error)
        return false
      }
    },
    
    // 更新本地用户信息（不调用API）
    updateLocalUserInfo(userData) {
      this.userInfo = { ...this.userInfo, ...userData }
      localStorage.setItem('user_info', JSON.stringify(this.userInfo))
      return true
    },
    
    // 更新头像
    updateAvatar(avatarUrl) {
      this.userInfo.avatar = avatarUrl
      localStorage.setItem('user_info', JSON.stringify(this.userInfo))
    },
    
    // 检查是否有某项权限
    hasPermission(permissionCode) {
      // 如果没有权限数组，返回false
      if (!this.permissions || this.permissions.length === 0) {
        return false
      }
      
      // 特殊处理，超级管理员拥有所有权限
      const isAdmin = this.userInfo.roles && this.userInfo.roles.some(role => role.code === 'admin')
      if (isAdmin) {
        return true
      }
      
      // 检查是否有特定权限
      return this.permissions.includes(permissionCode)
    },
    
    // 检查是否拥有某些权限中的任意一个
    hasAnyPermission(permissionCodes) {
      if (!permissionCodes || permissionCodes.length === 0) {
        return true // 如果没有指定权限要求，则默认通过
      }
      
      // 特殊处理，超级管理员拥有所有权限
      const isAdmin = this.userInfo.roles && this.userInfo.roles.some(role => role.code === 'admin')
      if (isAdmin) {
        return true
      }
      
      // 检查是否有特定权限中的任何一个
      return permissionCodes.some(code => this.permissions.includes(code))
    },
    
    // 检查是否拥有所有指定权限
    hasAllPermissions(permissionCodes) {
      if (!permissionCodes || permissionCodes.length === 0) {
        return true // 如果没有指定权限要求，则默认通过
      }
      
      // 特殊处理，超级管理员拥有所有权限
      const isAdmin = this.userInfo.roles && this.userInfo.roles.some(role => role.code === 'admin')
      if (isAdmin) {
        return true
      }
      
      // 检查是否有所有特定权限
      return permissionCodes.every(code => this.permissions.includes(code))
    }
  }
}) 